package com.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.wechat.entity.TransactionRecord;
import com.wechat.result.Result;
import com.wechat.service.TransactionRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * 模拟微信支付退款业务
 */
@RestController
@RequestMapping("/refund/domestic")
@Slf4j
public class RefundController {

    @Autowired
    private TransactionRecordService transactionRecordService;
    /**
     * 模拟退款业务
     * @param body
     * @return
     */
    @PostMapping("/refunds")
    public Result refunds(@RequestBody JSONObject body){
        log.info("模拟退款业务{}",body);
        TransactionRecord transactionRecord = transactionRecordService
                .lambdaQuery()
                .eq(TransactionRecord::getOutTradeNo, body.getString("out_trade_no"))
                .eq(TransactionRecord::getStatus, TransactionRecord.NORMAL)
                .one();
        if(transactionRecord == null){
            return Result.error("交易不存在");
        }
//        if(!Objects.equals(transactionRecord.getTotal(), body.getJSONObject("amount").getBigDecimal("total"))){
//            return Result.error("退款金额有误");
//        }
        //通知各方退款
        transactionRecord.setStatus(TransactionRecord.REFUND);
        transactionRecordService.updateById(transactionRecord);
        return Result.success("退款成功");
    }
}
